import {commonApi} from "../api";

class AudioHelper {
  constructor() {
    this.innerAudioContext = uni.createInnerAudioContext()
    try {
      this.innerAudioContext.obeyMuteSwitch = false
    } catch (e) {

    }
    this.innerAudioContext.onPlay(this.onPlay.bind(this))
    this.innerAudioContext.onEnded(this.onStop.bind(this))
    this.innerAudioContext.onStop(this.onStop.bind(this))
    this.innerAudioContext.onPause(this.onStop.bind(this))
    this.innerAudioContext.onError(this.onError.bind(this))
    this.innerAudioContext.onCanplay(() => {
      console.log('onCanplay')
    })
    this.statusChangeListeners = []
  }

  addStatusChange(onStatusChange) {
    this.statusChangeListeners.push(onStatusChange)
  }

  stopQuestion() {
    this.innerAudioContext.stop()
    this.onStatusChange(this.questionId, false)
    this.innerAudioContext.autoplay = false
  }

  onStatusChange(id, status) {
    for (let i = 0; i < this.statusChangeListeners.length; i++) {
      this.statusChangeListeners[i](id, status)
    }
  }

  onError(res) {
    console.log(res.errMsg);
    console.log(res.errCode);
  }

  onStop() {
    this.onStatusChange && this.onStatusChange(this.questionId, false)
  }

  onPlay() {
    console.log('onPlay')
    this.onStatusChange && this.onStatusChange(this.questionId, true)
  }

  async playQuestion(question, readRightAnswer, vip) {
    this.questionId = question.id
    let option = false
    let answer = false
    let jx = false
    if (readRightAnswer) {
      option = true
      answer = true
      jx = true
    }

    const res = await commonApi.questionYuyin(this.questionId, option, answer, jx, vip)
    this.innerAudioContext.src = res.data.data.url
    // this.innerAudioContext.autoplay = true
    this.innerAudioContext.play()
    console.log('play', res.data.data.url)
  }

  destroy() {
    this.innerAudioContext.destroy()
    this.onStatusChange = null
    this.question = null
  }
}


export default {
  _instance: null,

  create() {
    this._instance = new AudioHelper()
  },

  getInstance() {
    return this._instance
  },

  destroy() {
    if (this._instance) {
      this._instance.destroy()
      this._instance = null
    }
  }
}
